from django.shortcuts import render
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet
from django_redis import get_redis_connection

# Create your views here.
from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSSerialziers, SKUSearchSeializer, SKUHistorySerialzier
from goods.utils import PageNum


class CategoriesView(APIView):
    """
        面包屑导航分类数据获取
    """

    def get(self, request, pk):
        # 1、获取三级分类id
        # 2、查询三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)
        # 3、通过三级分类查询二级分类
        cat2 = cat3.parent
        # 4、通过二级分类查询依级分类
        cat1 = cat2.parent
        # 5、返回结果
        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,

        })


class SKUSView(ListAPIView):
    """
        获取当前分类的所有商品
    """
    serializer_class = SKUSSerialziers
    # queryset = SKU.objects.filter(category_id=pk)
    pagination_class = PageNum  # 分页
    filter_backends = [OrderingFilter]  # 过滤排序
    ordering_fields = ('create_time', 'sales', 'price')

    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


        # def get(self,request,pk):
        #     # 1、获取分类id
        #     # 2、查询属于这个分类所有商品对象
        #     # 3、序列化返回结果 分页和过滤排序


class SKUSearchView(HaystackViewSet):
    index_models = [SKU]
    serializer_class = SKUSearchSeializer

    pagination_class = PageNum


class SKUHistoryView(CreateAPIView,ListAPIView):
    """
        用户浏览历史记录
    """

    # serializer_class = SKUHistorySerialzier


    def get_queryset(self):
        # 1、获取用户
        user=self.request.user
        # 2、建立缓存连接
        conn=get_redis_connection('history')
        # 3、查询缓存数据获取到sku——id
        sku_ids=conn.lrange('history_%s'%user.id,0,100)
        # 4、根据sku——id查询商品对象
        skus=SKU.objects.filter(id__in=sku_ids)  # [1,2,3]
        return skus

    def get_serializer_class(self):
        # 不同请求反活力不同序列化器
        if self.request.method == "POST":
            return SKUHistorySerialzier

        else:
            return SKUSSerialziers
